package com.qq.mybatisdemo.configration;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MutiplyDataSource {

    @Bean(name = "dataSourcePrimary")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource getPrimaryDataSource(){
        return new HikariDataSource();

    }
    @Bean(name = "dataSourceLocal")
    @ConfigurationProperties(prefix = "spring.datasource.local")
    public DataSource getPrimaryDataSourceLocal(){
        return new HikariDataSource();

    }
    @Bean(name = "dataSourceProd")
    @ConfigurationProperties(prefix = "spring.datasource.prod")
    public DataSource getPrimaryDataSourceProd(){
            return new HikariDataSource();
    }
    @Primary
    @Bean(name = "dynamicDataSource")
    public DataSource getDynamicDataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultTargetDataSource(getPrimaryDataSource());
        Map<Object,Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("primary",getPrimaryDataSource());
        dataSourceMap.put("local",getPrimaryDataSourceLocal());
        dataSourceMap.put("prod",getPrimaryDataSourceProd());
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        return dynamicDataSource;
    }

    /**
     * 事务配置
     * @return
     */
    @Bean
    public PlatformTransactionManager getPlatformTransactionManager(){
        return  new DataSourceTransactionManager(getDynamicDataSource());
    }



}
